﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Xml.Linq;
using Wpf.Ui;
using Wpf.Ui.Controls;
using Wpf.Ui.Extensions;

namespace ClientAppraise.Controls;



public class ZxCardSearch : Panel
{
    public Size ChildSize;
    bool IsExpand = true;
    double ItemsPerRowCount;
    int RowCount;
    public static readonly DependencyProperty CommandProperty;

    public static readonly RoutedEvent SearchButtonClickEvent;

    public static readonly DependencyProperty ItemSizeProperty;
    public static readonly DependencyProperty ItemMarginProperty;


    static ZxCardSearch()
    {
        SearchButtonClickEvent = EventManager.RegisterRoutedEvent(nameof(SearchButtonClick), RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ZxCardSearch));

        ItemSizeProperty = DependencyProperty.Register(nameof(ItemSize), typeof(Size), typeof(ZxCardSearch), new PropertyMetadata(null));
        ItemMarginProperty = DependencyProperty.Register(nameof(ItemMargin), typeof(Thickness), typeof(ZxCardSearch), new PropertyMetadata(null));

        CommandProperty = DependencyProperty.Register(nameof(Command), typeof(ICommand), typeof(ZxCardSearch), new PropertyMetadata(null));
    }

    public event RoutedEventHandler SearchButtonClick
    {
        add => AddHandler(SearchButtonClickEvent, value);
        remove => RemoveHandler(SearchButtonClickEvent, value);
    }
    public ICommand Command
    {
        get
        {
            return (ICommand)GetValue(CommandProperty);
        }
        set
        {
            SetValue(CommandProperty, value);
        }
    }
    public Size ItemSize
    {
        get => (Size)GetValue(ItemSizeProperty);
        set => SetValue(ItemSizeProperty, value);
    }
    public Thickness ItemMargin
    {
        get => (Thickness)GetValue(ItemMarginProperty);
        set => SetValue(ItemMarginProperty, value);
    }

    readonly Wpf.Ui.Controls.Button ExpanderButton;
    readonly Wpf.Ui.Controls.Button SearchButton;

    public ZxCardSearch()
    {
        ExpanderButton = new Wpf.Ui.Controls.Button() { Icon = new SymbolIcon(SymbolRegular.ChevronDown48), BorderThickness = new Thickness(0) };
        SearchButton = new Wpf.Ui.Controls.Button() { Content = "查询", Appearance = ControlAppearance.Success, Margin = new Thickness() { Left = 5 } };
        ExpanderButton.Click += (object sender, RoutedEventArgs e) =>
        {
            OnExpanderButtonClick();
        };

        //SearchButton.Click += (object sender, RoutedEventArgs e) =>
        //{
        //    var args = new RoutedEventArgs(SearchButtonClickEvent);
        //    RaiseEvent(args);
        //};

        Binding binding = new()
        {
            Source = this,
            Path = new PropertyPath("Command")
        };

        SearchButton.SetBinding(Wpf.Ui.Controls.Button.CommandProperty, binding);

       // SearchButton.Command = this.Command;
    }

    protected override void OnInitialized(EventArgs e)
    {
        var formItem = new StackPanel() { VerticalAlignment = VerticalAlignment.Top, Orientation = Orientation.Horizontal, FlowDirection = FlowDirection.RightToLeft };
        InternalChildren.Add(formItem);

        formItem.Children.Add(ExpanderButton);
        formItem.Children.Add(SearchButton);
    }
    private void OnExpanderButtonClick()
    {
        IsExpand = !IsExpand;

        if (IsExpand)
        {
            ExpanderButton.Icon = new SymbolIcon(SymbolRegular.ChevronUp48);
        }
        else
        {
            ExpanderButton.Icon = new SymbolIcon(SymbolRegular.ChevronDown48);
        }

        InvalidateMeasure();
    }

    protected override Size MeasureOverride(Size availableSize)
    {
        UpdateChildSize(availableSize);
        availableSize.Height = RowCount * ChildSize.Height;
        return availableSize;
    }

    private void UpdateChildSize(Size availableSize)
    {
        ChildSize = CalculateChildSize(availableSize);
    }

    private Size CalculateChildSize(Size availableSize)
    {
        if (InternalChildren.Count == 0)
        {
            return new Size(0, 0);
        }

        ChildSize.Height = ItemSize.Height;
        var minWidthCount = Math.Floor(availableSize.Width / ItemSize.Width);

        minWidthCount = minWidthCount < 2 ? 2 : minWidthCount;

        //如果最后一行只有一个查询，那么，每行减少一个，
        //但这样也会有问题，可能会一行放不下，如果再放一行，那……………………
        // if(InternalChildren.Count- minWidthCount)


        ChildSize.Width = availableSize.Width / (InternalChildren.Count > minWidthCount ? minWidthCount : InternalChildren.Count);

        if (ChildSize.Width < ItemSize.Width)
        {
            ChildSize.Width = availableSize.Width;

            ItemsPerRowCount = 1;
            RowCount = 2;
        }
        else
        {
            ItemsPerRowCount = minWidthCount;
        }

        if (!IsExpand)
        {
            RowCount = (int)Math.Ceiling((double)InternalChildren.Count / ItemsPerRowCount);
        }
        else
        {
            if (ChildSize.Width < ItemSize.Width)
            {
                RowCount = 2;
            }
            else
            {
                RowCount = 1;
            }
        }

        var i = 0;

        foreach (FrameworkElement child in InternalChildren)
        {
            if (IsExpand && minWidthCount < InternalChildren.Count)
            {
                if (i >= minWidthCount - 1 && i != InternalChildren.Count - 1)
                {
                    child.Visibility = Visibility.Collapsed;//.Measure(new Size(0, 0));
                    child.Measure(new Size(0, 0));
                }
                else
                {
                    InternalChildren[i].Visibility = Visibility.Visible;
                    child.Measure(ChildSize);
                }
            }
            else
            {
                InternalChildren[i].Visibility = Visibility.Visible;
                child.Measure(ChildSize);
            }

            i++;
        }

        return ChildSize;
    }

    protected override Size ArrangeOverride(Size finalSize)
    {
        if (ItemMargin == default)
        {
            ItemMargin = new Thickness(0);
        }

        var i = 0;
        for (var j = 0; j < InternalChildren.Count; j++)
        {
            FrameworkElement child = (FrameworkElement)InternalChildren[j];

            if (child.Visibility == Visibility.Visible)
            {
                var currentRow = Math.Floor(i / ItemsPerRowCount);
                var pos = i % ItemsPerRowCount;

                var leftMargin = 0d;

                if (j == InternalChildren.Count - 1 && InternalChildren.Count > ItemsPerRowCount)
                {
                    var blank = ItemsPerRowCount - 1 - pos;
                    leftMargin = blank * ChildSize.Width;
                }
                //if(currentRow!= RowCount)
                //{
                child.Arrange(new Rect(pos * ChildSize.Width + ItemMargin.Left + leftMargin, currentRow * ChildSize.Height + ItemMargin.Top, ChildSize.Width - (ItemMargin.Left + ItemMargin.Right), ChildSize.Height - (ItemMargin.Top + ItemMargin.Bottom)));

                //}
                //else
                //{
                //    child.Arrange(new Rect(pos * ChildSize.Width + ItemMargin.Left + leftMargin, currentRow * ChildSize.Height + ItemMargin.Top, ChildSize.Width - (ItemMargin.Left + ItemMargin.Right), ChildSize.Height - (ItemMargin.Top + ItemMargin.Bottom)));
                //}

                i++;
            }
            else
            {
                child.Arrange(new Rect(0, 0, 0, 0));
            }
        }

        finalSize.Height = RowCount * ChildSize.Height - ItemMargin.Bottom;


        return finalSize;
    }
}
